package com.migu.contacts.util;

import android.text.TextUtils;

import com.frank.libandroid.GsonUtil;
import com.frank.libandroid.RetrofitUtil;
import com.migu.contacts.MainActivity;
import com.migu.contacts.bean.LoginRes;
import com.migu.contacts.bean.UserBean;
import com.migu.contacts.login.LoginActivity;
import com.tencent.mmkv.MMKV;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class UserCenter {
    public static UserBean userBean;

    public static void init() {
        String string = MMKV.defaultMMKV().getString(LoginResKey, "");
        if (!TextUtils.isEmpty(string)) {
            LoginRes res = GsonUtil.fromJson(string, LoginRes.class);
            setLoginRes(res);
        }
    }

    public static Class getStarter() {
        if (isLogin()) {
            return MainActivity.class;
        } else {
            return LoginActivity.class;
        }
    }

    public static final String Token = "token";
    public static final String LoginResKey = "LoginResKey";
    private static LoginRes loginRes;

    public static void setLoginRes(LoginRes loginRes) {
        UserCenter.loginRes = loginRes;
        MMKV.defaultMMKV().putString(LoginResKey, GsonUtil.toJson(loginRes));
        RetrofitUtil.token = loginRes.accessToken;
        isLogging = false;
    }

    public static boolean isVip() {
        String memberEndTime = userBean.memberEndTime;
        if (TextUtils.isEmpty(memberEndTime)) {
            return false;
        }
        try {
            LocalDateTime parse = LocalDateTime.parse(memberEndTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            return parse.isAfter(LocalDateTime.now());
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isLogin() {
        return loginRes != null;
    }

    public static boolean isLogging = false;

    public static LoginRes getLoginRes() {
        return loginRes;
    }

    public static void logout() {
        loginRes = null;
        RetrofitUtil.token = "";
        MMKV.defaultMMKV().putString(LoginResKey, "");
    }

    public static String getUserId() {
        return getLoginRes().userId;
    }
}
